﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using BBD_DAL.Core;
using BBD_DAL.Entities;
using DBFiller.UI;
using DBFiller.Entities;


namespace BBDApplication
{
	public partial class DatabaseWindow : Form
	{
		private DataContext dataContext;
		private List<DataReportClass> resultsClassList;
		private List<InfoReportClass> resultsTitleClass;
		private List<List<long>> countMainValueForSchool = new List<List<long>>();
		private List<SexReportClass> resultsSexClass;
		private List<List<long>> countStudentBySex = new List<List<long>>();
		private List<StudentsReportClass> resultsStudInfo;
		private List<OtherProgClass> resultsAntiProgClass;
		private List<long> countAntiAnswer = new List<long>();
		public DatabaseWindow()
		{
			InitializeComponent();
			for (int i = 1; i < ConfigurationManager.ConnectionStrings.Count; i++)
				connectionStringBox.Items.Add(new ComboBoxItem()
				{
					Name = ConfigurationManager.ConnectionStrings[i].Name,
					Value = ConfigurationManager.ConnectionStrings[i].ConnectionString
				});

			if (ConfigurationManager.ConnectionStrings.Count > 0)
				connectionStringBox.SelectedIndex = 0;
			
		}

		private void DatabaseWindow_Load(object sender, EventArgs e)
		{
			resultsClassList = new List<DataReportClass>();
			DataReportClassBindingSource.DataSource = resultsClassList;
			resultsTitleClass = new List<InfoReportClass>();
			infoReportClassBindingSource.DataSource = resultsTitleClass;
			resultsSexClass = new List<SexReportClass>();
			sexReportClassBindingSource.DataSource = resultsSexClass;
			resultsStudInfo = new List<StudentsReportClass>();
			studentsReportClassBindingSource.DataSource = resultsStudInfo;
			resultsAntiProgClass = new List<OtherProgClass>();
			otherProgClassBindingSource.DataSource = resultsAntiProgClass;
		}


		private void WojewodztwaInit()
		{
			List<State> wojewodztwa = dataContext.StateDao.List();
			
			wojewodztwo_cBox.Items.Add("Wszystkie");

			for (int i = 0; i < wojewodztwa.Count; i++)
			{
				wojewodztwo_cBox.Items.Add(wojewodztwa[i]);				
				wojewodztwo_cBox.SelectedIndex = 0;
			}

		}

		private void rodzajAnalizyInit()
		{
			rodzAnalizy_cBox.Items.Clear();
			rodzAnalizy_cBox.Items.Add("Ogolna");
			rodzAnalizy_cBox.Items.Add("Według szkół");
			rodzAnalizy_cBox.SelectedIndex = 0;
		}

		private void wojewodztwo_cBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			miasto_cBox.Items.Clear();
			miasto_cBox.Items.Add("Wszystkie");

			if (wojewodztwo_cBox.SelectedItem is string)
			{
				miasto_cBox.Items.AddRange(dataContext.CityDao.List().ToArray());
				
			}
			else
			{
				State selectedState = (State)wojewodztwo_cBox.SelectedItem;
				miasto_cBox.Items.AddRange(dataContext.CityDao.GetByState(selectedState.Id).ToArray());
			}

			miasto_cBox.SelectedIndex = 0;

		}

		private void miasto_cBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			szkoly_checkLBox.Items.Clear();

			if (miasto_cBox.SelectedItem is string)
			{
				for (int i = 1; i < miasto_cBox.Items.Count; i++)
				{
					List<School> schools = dataContext.SchoolDao.GetByCity((miasto_cBox.Items[i] as City).Id);
					if (schools != null)
						szkoly_checkLBox.Items.AddRange(schools.ToArray());
				}
			}
			else
			{
				City wybMiasto = (City)miasto_cBox.SelectedItem;
				long idCity = wybMiasto.Id;
				List<School> schools = dataContext.SchoolDao.GetByCity(idCity);
				if (schools != null)
					szkoly_checkLBox.Items.AddRange(schools.ToArray());
			}

		}

		private void generAnalizy_button_Click(object sender, EventArgs e)
		{
			this.groupBox1.Visible = false;
			
			
			//wojewodztwa
			String analiza = "Analizowane dane" + Environment.NewLine + "Wojewodztwa: " + Environment.NewLine;
			if (wojewodztwo_cBox.SelectedItem is string)
			{
				List<State> pom = dataContext.StateDao.List();

				for (int i = 0; i < pom.Count; i++)
				{
					analiza = analiza + pom[i].StateName.ToString() + ";\n";
				}
			}
			else
			{
				analiza = analiza + wojewodztwo_cBox.SelectedItem.ToString() + ";\n";
			}

			//miasta
			analiza = analiza + Environment.NewLine + "Miasta:" + Environment.NewLine;

			if (miasto_cBox.SelectedItem is string && wojewodztwo_cBox.SelectedItem is string)
			{

				List<City> pom = dataContext.CityDao.List();// GetByState(selectedState.Id);
				for (int i = 0; i < pom.Count; i++)
				{
					analiza = analiza + pom[i].CityName.ToString() + ",";
				}
			}
			else if (miasto_cBox.SelectedItem is string && wojewodztwo_cBox.SelectedItem is State)
			{
				State selectedState = (State)wojewodztwo_cBox.SelectedItem;
				List<City> pom = dataContext.CityDao.GetByState(selectedState.Id);

				for (int i = 0; i < pom.Count; i++)
				{
					analiza = analiza + pom[i].CityName.ToString() + ",";
				}
			}
			else
			{
				analiza = analiza + miasto_cBox.SelectedItem.ToString() + ",";
			}

			// szkoly
			analiza += Environment.NewLine + "Wybrano " + szkoly_checkLBox.CheckedItems.Count.ToString() + " szkoły: " + Environment.NewLine;
			List<string> schoolName = new List<string>();
			for (int i = 0; i < szkoly_checkLBox.CheckedItems.Count; i++)
			{
				schoolName.Add(szkoly_checkLBox.CheckedItems[i].ToString());
				analiza += schoolName[i] + ", ";
			}

			//Pobranie wszystkich pytan
			List<Question> QuestionList = dataContext.QuestionDao.List();
			int numberOfQuestion = QuestionList.Count;
			analiza +=Environment.NewLine + "Lista pytań:" + Environment.NewLine;
			for (int i = 0; i < QuestionList.Count; i++)
			{
				analiza = analiza + (i + 1).ToString() +". " + QuestionList[i].QuestionText + Environment.NewLine;
			}
			analiza += Environment.NewLine;

			///Analiza 
			List<List<Questionnaire>> questionnaireBySchool = new List<List<Questionnaire>>();
			School getSchool = new School();

			if (rodzAnalizy_cBox.SelectedItem.ToString() == "Według szkół" && !plec_checkBox.Checked)
			{
				this.groupBox1.Visible = true;
				raportSchool_cBox.Items.Clear();
				for (int i = 0; i < szkoly_checkLBox.CheckedItems.Count; i++)
				{
					raportSchool_cBox.Items.Add((School)szkoly_checkLBox.CheckedItems[i]);

				}
				
			}


			if (rodzAnalizy_cBox.SelectedItem.ToString() == "Według szkół")
			{
				analiza = analiza + Environment.NewLine + "Analiza przeprowadzona według szkol" + Environment.NewLine;

				for (int i = 0; i < szkoly_checkLBox.CheckedItems.Count; i++)
				{
					getSchool = (School)szkoly_checkLBox.CheckedItems[i];
					long idSchool = getSchool.Id;
					questionnaireBySchool.Add(dataContext.QuestionnaireDao.GetBySchool(idSchool));
				}
			}
			else
			{
				analiza = analiza + Environment.NewLine + "Analiza sumaryczna" + Environment.NewLine;
				List<Questionnaire> questionnaire = new List<Questionnaire>();
				for (int i = 0; i < szkoly_checkLBox.CheckedItems.Count; i++)
				{
					getSchool = (School)szkoly_checkLBox.CheckedItems[i];
					long idSchool = getSchool.Id;
					questionnaire.AddRange(dataContext.QuestionnaireDao.GetBySchool(idSchool));

				}
				questionnaireBySchool.Add(questionnaire);
			}


            //uwzglednieniem plci lub dla danych
			if (plec_checkBox.Checked)
			{
				answer_dataGridView.Columns.Clear();
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[0].HeaderText = "Id. pytania";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[1].HeaderText = "Płeć";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[2].HeaderText = "Szkoła";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[3].HeaderText = "Odp. 'tak'";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[4].HeaderText = "Odp. 'nie'";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[5].HeaderText = "Brak odp.";

				analiza += "Wyniki według płci:" + Environment.NewLine;
				Sex[] sex = {Sex.Female, Sex.Male};
				string[] sexString = { "Kobiety", "Mężczyźni" };
				for (int i = 0; i < 2; i++)
				{

					List<List<Answer>> allQuestionAnswers = new List<List<Answer>>();
					for (int j = 0; j < questionnaireBySchool.Count; j++)
					{
						List<Answer> questionAnswer = new List<Answer>();
						for (int k = 0; k < questionnaireBySchool[j].Count; k++)
						{
							List<Answer> answer = new List<Answer>();
							long idQuestionnaire =questionnaireBySchool[j][k].Id; 
							if (questionnaireBySchool[j][k].Sex == sex[i])
							{
								answer = dataContext.AnswerDao.GetByQuestionnaire(idQuestionnaire);
							}
							if (answer != null)
							{
								questionAnswer.AddRange(answer);

							}
						}
						allQuestionAnswers.Add(questionAnswer);
					}

					analiza = analiza + sexString[i] + Environment.NewLine;
					string answerAnalize = dataAnalize(allQuestionAnswers, schoolName, sexString[i], numberOfQuestion);
					analiza += answerAnalize;
				}


			}
			else
			{
				countStudentBySex.Clear();
				Sex[] sex = { Sex.Female, Sex.Male};

				for (int j = 0; j < questionnaireBySchool.Count; j++)
				{
					countStudentBySex.Add(new List<long>());
					long tmpCountSex = 0;
					long summaryStud = 0;

					for (int i = 0; i < 2; i++)
					{
						for (int k = 0; k < questionnaireBySchool[j].Count; k++)
						{
							long idQuestionnaire = questionnaireBySchool[j][k].Id;
							if (questionnaireBySchool[j][k].Sex == sex[i])
							{
								tmpCountSex++;
							}

						}
						countStudentBySex[j].Add(tmpCountSex);
						summaryStud +=tmpCountSex;
						tmpCountSex = 0;
					
					}
					countStudentBySex[j].Add(questionnaireBySchool[j].Count - summaryStud);
				}

				answer_dataGridView.Columns.Clear();
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[0].HeaderText = "Id. pytania";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[1].HeaderText = "Szkoła";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[2].HeaderText = "Odp. 'tak'";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[3].HeaderText = "Odp. 'nie'";
				answer_dataGridView.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()));
				answer_dataGridView.Columns[4].HeaderText = "Brak odp.";

				List<List<Answer>> allQuestionAnswers = new List<List<Answer>>();
				for (int j = 0; j < questionnaireBySchool.Count; j++)
				{
					List<Answer> questionAnswer = new List<Answer>();
					for (int i = 0; i < questionnaireBySchool[j].Count; i++)
					{
						long idQuestionnaire = questionnaireBySchool[j][i].Id;
						List<Answer> answer = dataContext.AnswerDao.GetByQuestionnaire(idQuestionnaire);
						if (answer != null)
						{
							questionAnswer.AddRange(answer);

						}
					}
					allQuestionAnswers.Add(questionAnswer);
				}
				analiza += dataAnalize(allQuestionAnswers, schoolName, null ,numberOfQuestion);

			}

			analize_textBox.Text = analiza;

		}



		private string dataAnalize(List<List<Answer>> allQuestionAnswers, List<string> schoolName, string sexString, int numberOfQuestion)
		{
			countMainValueForSchool.Clear();
			countAntiAnswer.Clear();
			List<List<List<long>>> allCountAnswer = new List<List<List<long>>>();
			string analiza = "";
			int[] tmp = { 0, 3, 7, 11, 14 };

			for (int i = 0; i < allQuestionAnswers.Count; i++)
			{
				
				countMainValueForSchool.Add(new List<long>());
				if (rodzAnalizy_cBox.SelectedItem.ToString() == "Według szkół")
				{
					analiza = analiza + "Szkoła: " + schoolName[i] + Environment.NewLine;

				}
				analiza = analiza + "Nr_pyt	|tak	|nie	|brak_odp" + Environment.NewLine;

				long[][] countAnswer = new long[numberOfQuestion][];
				for (int j = 0; j < numberOfQuestion; j++)
				{
					countAnswer[j] = new long[3];
					countAnswer[j][0] = (long)0;
					countAnswer[j][1] = (long)0;
					countAnswer[j][2] = (long)0; 
				}

				for (int j = 0; j < allQuestionAnswers[i].Count; j++)
				{
					switch (allQuestionAnswers[i][j].Question.Id)
					{
						case 1:
						case 4:
						case 7:
						case 8:
						case 11:
						case 12:
						case 14:
						case 15:
						case 17:
							if (allQuestionAnswers[i][j].GivenAnswer == true)
							{
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][0] += 1;
							}
							else if (allQuestionAnswers[i][j].GivenAnswer == false)
							{
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][1] += 1;
							}
							else
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][2] += 1;

							break;
						case 2:
						case 5:
						case 9:
						case 13:
						case 16:
							if (allQuestionAnswers[i][j - 1].GivenAnswer == true && allQuestionAnswers[i][j].GivenAnswer == true)
							{
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][0] += 1;
							}
							else if (allQuestionAnswers[i][j - 1].GivenAnswer == true && allQuestionAnswers[i][j].GivenAnswer == false)
							{
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][1] += 1;
							}
							else if (allQuestionAnswers[i][j - 1].GivenAnswer == true && allQuestionAnswers[i][j].GivenAnswer == null)
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][2] += 1;
							break;

						case 3:
						case 6:
						case 10:
							if (allQuestionAnswers[i][j - 2].GivenAnswer == true && allQuestionAnswers[i][j].GivenAnswer == true)
							{
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][0] += 1;
							}
							else if (allQuestionAnswers[i][j - 2].GivenAnswer == true && allQuestionAnswers[i][j].GivenAnswer == false)
							{
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][1] += 1;
							}
							else if (allQuestionAnswers[i][j - 2].GivenAnswer == true && allQuestionAnswers[i][j].GivenAnswer == null)
								countAnswer[allQuestionAnswers[i][j].Question.Id - 1][2] += 1;

							break;
						default:
							break;
					}
				}
				countAntiAnswer.Add(countAnswer[16][0]);

				allCountAnswer.Add(new List<List<long>>());
				for (int j = 0; j < numberOfQuestion; j++)
				{

					allCountAnswer[i].Add(new List<long>());
					allCountAnswer[i][j].AddRange(countAnswer[j]);

					if (j == 1 || j == 4 || j == 8 || j == 12 || j == 15)
					{
						analiza += "W tym dla odp. 'tak':" + Environment.NewLine + "	";
					}
					else if (j == 2 || j == 5 || j == 9  )
					{
						analiza += "	";
					}

					analiza = analiza + (j + 1).ToString() + ".";
					for (int k = 0; k < 3; k++)
					{
						analiza = analiza + "	|" + allCountAnswer[i][j][k].ToString();
					}
					analiza += Environment.NewLine + Environment.NewLine;

				}


				for (int j = 0; j < tmp.Length; j++)
				{
					countMainValueForSchool[i].Add(allCountAnswer[i][tmp[j]][0]);
				}

				for (int j = 0; j < numberOfQuestion; j++) 
                {
					if (answer_dataGridView.Columns.Count == 6)
					{
						string[] cell = new string[answer_dataGridView.Columns.Count];
						cell[0] = (j + 1).ToString();
						cell[1] = sexString;
						cell[2] = rodzAnalizy_cBox.SelectedItem.ToString()=="Według szkół"? schoolName[i]: "ogółem";
						cell[3] = countAnswer[j][0].ToString();
						cell[4] = countAnswer[j][1].ToString();
						cell[5] = countAnswer[j][2].ToString();
						answer_dataGridView.Rows.Add(cell);
					}
					else
					{
						string[] cell = new string[answer_dataGridView.Columns.Count];
						cell[0] = (j + 1).ToString();
						cell[1] = rodzAnalizy_cBox.SelectedItem.ToString() == "Według szkół" ? schoolName[i] : "ogółem";
						cell[2] = countAnswer[j][0].ToString();
						cell[3] = countAnswer[j][1].ToString();
						cell[4] = countAnswer[j][2].ToString();
						answer_dataGridView.Rows.Add(cell);
					}
                }
                answer_dataGridView.Invalidate();
				
			}
			return analiza;
		}



		private void importujToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MainWindow filler = new MainWindow();
			filler.ShowDialog();
		}

		private void aktualizujConnectionStringToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dataContext = new DataContext(((ComboBoxItem)connectionStringBox.SelectedItem).Value.ToString());
			this.WojewodztwaInit();
			this.groupBoxPlci.Visible =
			this.groupBox2.Visible =
			this.groupBox3.Visible =
			this.wojewodztwo_cBox.Enabled=
			this.miasto_cBox.Enabled =
			this.szkoly_checkLBox.Enabled = true;
			this.rodzajAnalizyInit();
			
			this.aktualizujConnectionStringToolStripMenuItem.Text = "Aktualizuj ConnectionString";
		}

		private void szkoly_checkLBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (szkoly_checkLBox.CheckedItems.Count != 0)
			{
				this.generAnalizy_button.Enabled = true;
				

			}
			else
			{
				this.generAnalizy_button.Enabled = false;
				this.generReport_button.Enabled = false;

			}
		}

		private void generReport_button_Click(object sender, EventArgs e)
		{
			resultsClassList.Clear();
			resultsTitleClass.Clear();
			resultsSexClass.Clear();
			for (int j = 0; j < countMainValueForSchool[raportSchool_cBox.SelectedIndex].Count; j++)
			{
				resultsClassList.Add(new DataReportClass(countMainValueForSchool[raportSchool_cBox.SelectedIndex][j].ToString()));
					
			}
			School schoolReport = (School)raportSchool_cBox.Items[raportSchool_cBox.SelectedIndex];
			string titleText = schoolReport.SchoolName + Environment.NewLine + "w " +dataContext.CityDao.Get(schoolReport.City.Id).CityName.ToString()  +"     " + Environment.NewLine;
			resultsTitleClass.Add(new InfoReportClass(titleText));

			long sumStudents = 0;
			for (int j = 0; j < 3; j++)
			{
				resultsSexClass.Add(new SexReportClass(countStudentBySex[raportSchool_cBox.SelectedIndex][j].ToString()));
				sumStudents+=countStudentBySex[raportSchool_cBox.SelectedIndex][j];
			
			}
			string txtStud = "W badaniu udział wzięło "+ sumStudents.ToString() + " uczniów";
			resultsStudInfo.Add(new StudentsReportClass(txtStud));
			string txtAtiProg = countAntiAnswer[raportSchool_cBox.SelectedIndex].ToString() + " uczniów zadeklarowało, że w ostatnim roku brało udział w dowolnym programie antynikotynowym.";
			resultsAntiProgClass.Add(new OtherProgClass(txtAtiProg));
			this.reportViewer1.RefreshReport();

		}

		private void raportSchool_cBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.generReport_button.Enabled = true;
		}
	}
}
